package com.zmn.oms.third.dj58.util;

import com.alibaba.fastjson.JSON;
import com.zmn.common.utils.encode.EncodeUtil;
import com.zmn.oms.common.utils.HttpUtil;
import com.zmn.oms.third.core.tracker.FacadeTracker;
import com.zmn.oms.third.dj58.DaoJia58Consts;
import com.zmn.oms.third.dj58.dto.api.DaoJia58Response;
import com.zmn.oms.third.dj58.dto.api.DaoJia58SendRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

/**
 * 类描述：生成签名和验证签名等工具类
 *
 * @author xiewenbing
 * @date 2019/11/04 16:40
 */
@Slf4j
public class DaoJia58Util {


    /**
     * 验证签名
     * @param sign
     * @param nonce
     * @param timestamp
     * @return boolean
     */
    public static boolean verifyRequestSign(String sign,String nonce,String timestamp) {
        if (Objects.isNull(sign) || sign.isEmpty()) {
            return false;
        }

        String valueSign = nonce + timestamp + DaoJia58Consts.TOKEN;
        String md5Sign = EncodeUtil.getMD5For32(valueSign);

        return sign.compareToIgnoreCase(md5Sign) == 0 ? true : false;
    }

    /**
     * 生成签名
     * @return String
     */
    public static String makeRequestSign(DaoJia58SendRequest daoJia58SendRequest){
        if (Objects.isNull(daoJia58SendRequest)) {
            return null;
        }

        // 测试代码
        // String secretDj58 = "9900e5a83e744654a0aaa41d0d903b99";
        String secretDj58 = DaoJia58Consts.SECRET;
        String signContent = secretDj58 + "accessToken" + daoJia58SendRequest.getAccessToken()
                + "daojiaJson" + daoJia58SendRequest.getDaojiaJson().toJSONString() + "format" + daoJia58SendRequest.getFormat()
                + "serviceKey" + daoJia58SendRequest.getServiceKey() + "timestamp" + daoJia58SendRequest.getTimestamp()
                + secretDj58;

        String signValue = DigestUtils.md5Hex(signContent);

        log.info("【{}-API】 消息加密签名内容:[{}]，签名:[{}]",DaoJia58Consts.CHANNEL_NAME,signContent,signValue);
        return signValue.toUpperCase();
    }

    /**
     * 给58到家服务发送请求
     * @param pathRequst
     * @param paramRequest
     * @return String
     */

    public static DaoJia58Response sendRequstToDaoJia58(String pathRequst,String paramRequest) {

        // 测试代码
        // String urlRequest = "http://openapi68.djtest.cn/api" + pathRequst;
        String urlRequest = DaoJia58Consts.API_URL + pathRequst;
        String httpResponse;

        try {
            log.info("【{}-API】<API请求> Url:[{}] RequestBody:[{}]", DaoJia58Consts.CHANNEL_NAME, urlRequest, paramRequest);
            FacadeTracker.FacadeTrackerCore tracker = FacadeTracker.getTracker()
                    .reqSummary(paramRequest);

            httpResponse = HttpUtil.httpPost(urlRequest, paramRequest);

            tracker.respSummary(httpResponse);
            log.info("【{}-API】<API响应> ResponseBody:[{}]", DaoJia58Consts.CHANNEL_NAME, httpResponse);
        } catch (Exception e) {
            log.info("【{}-API】 请求失败:[{}]", DaoJia58Consts.CHANNEL_NAME, e.getMessage());
            log.error(e.getMessage(), e);

            return null;
        }

        DaoJia58Response daoJia58Response = JSON.parseObject(httpResponse,DaoJia58Response.class);
        if (Objects.isNull(daoJia58Response)) {
            log.info("【{}-API】 解析返回数据失败", DaoJia58Consts.CHANNEL_NAME);
            return null;
        }

        if (daoJia58Response.getCode() != DaoJia58Consts.ZMN_RETURN_CODE_SUCCESS ) {
            log.info("【{}-API】 返回提示错误，错误代码:[{}]，错误提示消息:[{}]", DaoJia58Consts.CHANNEL_NAME,daoJia58Response.getCode(),daoJia58Response.getMessage());
        }

        return daoJia58Response;
    }

    /**
     * 获取时间戳
     * @return String
     */
    public static String getTimestamp() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return simpleDateFormat.format(new Date());
    }
}
